package com.bodacn.packapp;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;

import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentF extends Fragment implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    //用于将Activity中的参数传给Fragment
    public static final int msgFocusBarcode = 1001;
    private static final int msgDetail=1002;
    private static final int msgGetOrderListOver=1003;
    private static final int msgGetBoxNeedListOver=1004;
    private static final int MSG_CallAcc =1005;
    private static final int MSG_ERROR=9005;
    private static final int msgGetColorListOver=9006;
    private ProgressDialog waitDialog = null;
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    EditText edt_checkReal,edt_item,edt_number;
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curDepart="",curDepartNo="",curLoginUserNo="",curLoginUser="",curServiceUrl="",curTermNo="00000",curServiceDir="",CPUID="";
    String selectWorkGroup="",callType="Normal";
    ListView detailList;
    View contentView;
    PopupWindow popupWindow;
    ListView lv_Detail;
    int topLeftLinerLayoutWidth=0;
    JSONArray orderJSON,detailJSON,headJSON,departJSON,boxNeedJSON,resultJSON;
    String selOrderNo="",selStyleNo="",selPO="",selBoxType="",selBoxFormat="",selColorNo="",selSize="",selItem="",selPort="",
            selTotalNum="0";
    EditText edt_WorkGroup;
    LinearLayout templetlisthead,mainLinerLayout;
    TextView tv_pop_title;
    TextView txt_OrderNo,txt_StyleNo,txt_PO;
    EditText edt_pop_orderNo,edt_pop_styleNo;
    ReentrantLock reentrantLock = new ReentrantLock();
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentF() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerF(new MainActivity.OnTransParamsListenerF() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                System.out.println("FragmentD:"+mParams);
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d("FragmentD","LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curTermNo=mParams.get("TermNo").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d("FragmentD","LoginParam------------------>2");
                            Log.d("FragmentC","LoginParam------------------>2");
                            edt_WorkGroup.setText(curDepart);
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.sendMessage(msg);
                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    private void initPopwindow() {
        selOrderNo="";selStyleNo="";selPO="";
        selItem="";
        popupWindow = new PopupWindow(contentView, -1, -2);
        popupWindow.setFocusable(true);
        contentView.findViewById(R.id.btn_pop_ok).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {
                if (tv_pop_title.getText().toString().equals("合约信息")) {
                    if (selOrderNo.length() > 0 && selStyleNo.length() > 0) {
                        txt_OrderNo.setText(selOrderNo);
                        txt_StyleNo.setText(selStyleNo);
                        txt_PO.setText(selPO);
                        SearchDetail();
                        if (popupWindow != null && popupWindow.isShowing()) popupWindow.dismiss();
                    } else {
                        curToast.setText("请选择需要的合约信息！");
                        curToast.show();
                    }
                } else{
                    System.out.println("selColorNo:"+selColorNo+" selSize:"+selSize);
                    if (selColorNo.length() > 0 && selSize.length() > 0) {
                        //消失数窗口
                        if (popupWindow != null && popupWindow.isShowing()) popupWindow.dismiss();
                        //调呼叫信息
                        showManuCallBox();

                    } else {
                        curToast.setText("请选择需要呼叫的颜色尺码信息！");
                        curToast.show();
                    }
                }
            }
        });
        contentView.findViewById(R.id.btn_pop_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {
                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        edt_pop_orderNo=contentView.findViewById(R.id.edt_pop_orderNo);
        edt_pop_styleNo=contentView.findViewById(R.id.edt_pop_styleNo);
        tv_pop_title = (TextView)contentView.findViewById(R.id.tv_pop_title);
        lv_Detail = (ListView)contentView.findViewById(R.id.lv_Detail);

        templetlisthead = (LinearLayout)contentView.findViewById(R.id.templetlisthead);
        popupWindow.setBackgroundDrawable((Drawable)new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_f, container, false);
        contentView = inflater.inflate(R.layout.popselect, container, false);
        InitView(root);
        System.out.println("fragment_f_onCreateView-"+curDepart);
        //更新当前组别
        edt_WorkGroup.setText(curDepart);
        return root;
    }
    //初始化;
    public void InitView(View view){
        //界面Edit;
        view.findViewById(R.id.btn_SelectGroup).setOnClickListener(this);
        view.findViewById(R.id.btn_SelectOrderNo).setOnClickListener(this);
        view.findViewById(R.id.btn_Call).setOnClickListener(this);
        view.findViewById(R.id.btn_Cancel).setOnClickListener(this);
        view.findViewById(R.id.btn_Query).setOnClickListener(this);
        view.findViewById(R.id.btn_unUccCall).setOnClickListener(this);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        detailList=view.findViewById(R.id.detailList);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    System.out.println(boxNeedJSON.optJSONObject(position));
                    if (boxNeedJSON.optJSONObject(position).has("OrderNo"))  selOrderNo=boxNeedJSON.optJSONObject(position).getString("OrderNo");
                    if (boxNeedJSON.optJSONObject(position).has("StyleNo"))  selStyleNo=boxNeedJSON.optJSONObject(position).getString("StyleNo");
                    if (boxNeedJSON.optJSONObject(position).has("PO"))  selPO=boxNeedJSON.optJSONObject(position).getString("PO");
                    if (boxNeedJSON.optJSONObject(position).has("BoxType"))  selBoxType=boxNeedJSON.optJSONObject(position).getString("BoxType");
                    if (boxNeedJSON.optJSONObject(position).has("BoxFormat"))  selBoxFormat=boxNeedJSON.optJSONObject(position).getString("BoxFormat");
                    if (boxNeedJSON.optJSONObject(position).has("ColorNo"))  selColorNo=boxNeedJSON.optJSONObject(position).getString("ColorNo");
                    if (boxNeedJSON.optJSONObject(position).has("Size"))  selSize=boxNeedJSON.optJSONObject(position).getString("Size");
                    if (boxNeedJSON.optJSONObject(position).has("Item"))  selItem=boxNeedJSON.optJSONObject(position).getString("Item");
                    if (boxNeedJSON.optJSONObject(position).has("Number"))  selTotalNum=boxNeedJSON.optJSONObject(position).getString("Number");
                    if (boxNeedJSON.optJSONObject(position).has("Port"))  selPort=boxNeedJSON.optJSONObject(position).getString("Port");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //别的功能键
        mainLinerLayout=view.findViewById(R.id.mainLinerLayout);
        edt_WorkGroup=view.findViewById(R.id.edt_WorkGroup);

        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_unUccCall:
                if (txt_OrderNo.getText().toString().length()>0) {
                    showSelectColorSize();
                } else {
                    curToast.setText("请先选择合约!");
                    curToast.show();
                }
                break;
            case R.id.btn_SelectGroup:
                showSelectGroup();
                break;
            case R.id.btn_SelectOrderNo:
                showSelectOrder();
                break;
            case R.id.btn_EditBarcode:
                break;
            case R.id.btn_Query:
                SearchDetail();
                break;
            case R.id.btn_Call:
                if (boxNeedJSON==null){
                    curToast.setText("请先查询出需要呼叫的装箱信息!");
                    curToast.show();
                    return;
                }
                System.out.println("selOrderNo:"+selOrderNo+" selBoxType:"+selBoxType);
                if (selOrderNo.length()>0&&selBoxType.length()>0)
                    showCallBox();
                else{
                    curToast.setText("请先选择要装箱的PO尺码信息!");
                    curToast.show();
                }
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = v.findViewById(v.getId());
                edt_checkReal.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (edt_checkReal.getText().length() > 0) {
                    edt_checkReal.setSelection(edt_checkReal.getText().length());
                    int start = edt_checkReal.getSelectionStart();
                    edt_checkReal.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_clearBtn:
                edt_checkReal.setText("");
                break;
            case R.id.btn_AffirmCall:
                System.out.println("callType:"+callType);
                if (callType.equals("Normal")) {
                    if (edt_number.getText().length() > 0)
                        CallAcc("Call", edt_number.getText().toString());
                }
                else {
                    selItem=edt_item.getText().toString();
                    CallManuAcc("Call",edt_number.getText().toString());
                }
                break;
            case R.id.btn_Cancel:
                if (boxNeedJSON==null){
                    curToast.setText("请先查询出需要取消的装箱呼叫记录!");
                    curToast.show();
                    return;
                }
                if (selOrderNo.length()>0&&selBoxType.length()>0){
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage("确定取消呼叫吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    CallAcc("Cancel","0");
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                else{
                    curToast.setText("请先选择要取消的装箱信息!");
                    curToast.show();
                }
                break;
            default:
                break;
        }
    }
    private void CallManuAcc(String transType,String paramNeedNum) {
        if (paramNeedNum.length()>0&&selItem.length()>0) {
            //执行SQL过程
            //执行SQL过程
            String SqlComm="Exec KeyPoint_Pack_CallNeedAcc @OperType='CallNeedAcc',@TransType='" + transType
                    +"', @TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                    + "',@WorkGroup='" + curDepart
                    + "',@OrderNo='" + txt_OrderNo.getText().toString()
                    + "',@StyleNo='" + txt_StyleNo.getText().toString()
                    + "',@PO='" +  txt_PO.getText().toString()
                    + "',@BoxFormat='',@BoxType='',@item='" + selItem
                    + "',@ColorNo='" + selColorNo+ "',@Size='" + selSize+ "',@Port='" + selPort
                    + "',@TotalNum='0',@NeedNum='" + paramNeedNum +"',@UserNo='"+curLoginUserNo+"'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else{
            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("系统提示").setMessage("请输入需求需求数及Item!")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                    }).create(); // 创建对话框
            alertDialog.show(); // 显示对话框
        }
    }
    private void CallAcc(String transType,String paramNeedNum) {
        if (paramNeedNum.length()>0) {
            //执行SQL过程
            //执行SQL过程
            String SqlComm="Exec KeyPoint_Pack_CallNeedAcc @OperType='CallNeedAcc',@TransType='" + transType +"', @TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                    + "',@WorkGroup='" + curDepart
                    + "',@OrderNo='" + selOrderNo+ "',@StyleNo='" + selStyleNo+ "',@PO='" + selPO
                    + "',@BoxFormat='" + selBoxFormat+ "',@BoxType='" + selBoxType+ "',@item='" + selItem
                    + "',@ColorNo='" + selColorNo+ "',@Size='" + selSize+ "',@Port='" + selPort
                    + "',@TotalNum='" + selTotalNum+ "',@NeedNum='" + paramNeedNum
                    +"',@UserNo='"+curLoginUserNo+"'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else{
            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("系统提示").setMessage("请输入需求装箱需求数!")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                    }).create(); // 创建对话框
            alertDialog.show(); // 显示对话框
        }
    }

    //查询明细;
    private void SearchDetail() {
        waitDialog.setMessage("准备刷新数据,请稍等");
        waitDialog.show();
        try {
            boxNeedJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SqlComm="Exec KeyPoint_Pack_GetBoxNeed @OperType='AccNeed',@TermNo='" + curTermNo
                + "',@WorkGroup='" + curDepart
                + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@OrderNo='" + txt_OrderNo.getText().toString()
                + "',@StyleNo='" + txt_StyleNo.getText().toString()
                + "',@PO='" + txt_PO.getText().toString()
                + "',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新订单初始化列表;
    private void refreshDepartData()
    {
        try {
            departJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SqlComm="Exec KeyPoint_Pack_GetDepart @TermNo='" + curTermNo + "',@WorkGroup='" + edt_WorkGroup.getText().toString() + "',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }
    //显示工序选择
    private void showSelectGroup(){
        selectWorkGroup="";
        System.out.println("departJSON:"+departJSON);
        if (departJSON==null||departJSON.length()==0){
            curToast.setText("没有组别信息,正在刷新稍后再试...");
            curToast.show();
            refreshDepartData();
            return;
        }
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View select_proc=inflater.inflate(R.layout.select_workgroup, null);

        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final GridView selectGrid=(GridView)select_proc.findViewById(R.id.selectGrid);
        final SelectGridAdapter selectGridAdapter=new SelectGridAdapter(getContext());
        selectGrid.setAdapter(selectGridAdapter);
        selectGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selectWorkGroup=departJSON.getJSONObject(position).getString("Department");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(select_proc).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selectWorkGroup.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            //置当前工序名称;
                            edt_WorkGroup.setText(selectWorkGroup);
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请通过点击选中需要切换的组别！");
                            curToast.show();
                        }
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.v("tag","取消");
            }
        }).setTitle("组别选择");
        final AlertDialog dialog =builder.create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 800;
        params.height = 500 ;
        dialog.getWindow().setAttributes(params);
    }

    //订单表格适配器;
    public final class SelectGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return departJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return departJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.select_workgroup_item, null, false);
            convertView.setLayoutParams(new GridView.LayoutParams((int)140,(int)(50)));
            convertView.setBackground(getResources().getDrawable(R.drawable.row_selector));
            try {
                Log.d(TAG,"getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_selgroup_name);// 显示文字
                if (departJSON.optJSONObject(0).has("Department")==true)
                    tv.setText(departJSON.optJSONObject(position).get("Department").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d(TAG,"SelectGridAdapter_position:"+position);
            return convertView;
        }
    }
    private void showSelectOrder(){
        //先显示对话框,再调用查询加载
        initPopwindow();
        try {
            orderJSON=new JSONArray("[]");
            headJSON = new JSONArray("[{\"TitleName\":\"OrderNo\",\"TitleText\":\"合约号\",\"TxtSize\":20,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Main\"}," +
                    "{\"TitleName\":\"StyleNo\",\"TitleText\":\"货号\",\"TxtSize\":20,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"PO\",\"TitleText\":\"PO\",\"TxtSize\":20,\"TxtWidth\":150,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"}]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        tv_pop_title.setText("合约信息");
        contentView.findViewById(R.id.linear_pop_search).setVisibility(View.VISIBLE);
        contentView.findViewById(R.id.btn_pop_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchSelectOrder(edt_pop_orderNo.getText().toString(),edt_pop_styleNo.getText().toString());
            }
        });
        CreateListHead();
        lv_Detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int postion, long param1Long) {
                try {
                    view.setSelected(true);
                    if (detailJSON.optJSONObject(postion).has("OrderNo") == true) {
                        selOrderNo = detailJSON.optJSONObject(postion).getString("OrderNo");
                    }
                    if (detailJSON.optJSONObject(postion).has("StyleNo") == true) {
                        selStyleNo = detailJSON.optJSONObject(postion).getString("StyleNo");
                    }
                    if (detailJSON.optJSONObject(postion).has("PO") == true) {
                        selPO = detailJSON.optJSONObject(postion).getString("PO");
                    }
                } catch (JSONException jSONException) {
                    jSONException.printStackTrace();
                }
            }
        });
        //控制屏幕宽度
        int deviationX=800,deviationY=600;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER,0,0);
        //加载默认的历史合约;
        SearchSelectOrder("","");
    }

    private void showSelectColorSize(){
        //先显示对话框,再调用查询加载
        initPopwindow();
        try {
            orderJSON=new JSONArray("[]");
            headJSON = new JSONArray("[{\"TitleName\":\"Color\",\"TitleText\":\"颜色\",\"TxtSize\":20,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Main\"}," +
                    "{\"TitleName\":\"Size\",\"TitleText\":\"尺码\",\"TxtSize\":20,\"TxtWidth\":150,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"}]");
            detailJSON=orderJSON;
            SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(getContext());
            lv_Detail.setAdapter(selectTempletListAdapter);
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        tv_pop_title.setText("颜色尺码信息");
        contentView.findViewById(R.id.linear_pop_search).setVisibility(View.GONE);
        CreateListHead();
        lv_Detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int postion, long param1Long) {
                try {
                    view.setSelected(true);
                    if (detailJSON.optJSONObject(postion).has("Color") == true) {
                        selColorNo = detailJSON.optJSONObject(postion).getString("Color");
                    }
                    if (detailJSON.optJSONObject(postion).has("Size") == true) {
                        selSize = detailJSON.optJSONObject(postion).getString("Size");
                    }

                } catch (JSONException jSONException) {
                    jSONException.printStackTrace();
                }
            }
        });
        //控制屏幕宽度
        int deviationX=600,deviationY=500;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER,0,0);
        //加载默认的历史合约;
        SearchSelectColorSize();
    }
    //过滤订单
    private void SearchSelectOrder(String paramOrderNo,String paramStyleNo) {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_GetOrderList @OperType='OrderList',@TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + paramOrderNo+ "',@StyleNo='" + paramStyleNo+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }
    //过滤订单
    private void SearchSelectColorSize() {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_GetColorSizeList @OperType='ColorList',@TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + txt_OrderNo.getText().toString()+ "',@StyleNo='" + txt_StyleNo.getText().toString()
                + "',@PO='" + txt_PO.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }
    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    //创建列;
    private void CreateListHead() {
        System.out.println("CreateListHead()");
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        System.out.println("CreateListHead()"+i);
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return detailJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<detailJSON.length())
                    return detailJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.popselect_item, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,dp2px(45)));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<detailJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (detailJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = detailJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (detailJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= detailJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }


    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return boxNeedJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return boxNeedJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_f_listitem, null, false);


            String tmpValue;
            try {
                Log.d(TAG,"getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_OrderNo);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("OrderNo")) tv.setText(boxNeedJSON.optJSONObject(position).get("OrderNo").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_PO);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("PO")) tv.setText(boxNeedJSON.optJSONObject(position).get("PO").toString());
                 tv = (TextView) convertView.findViewById(R.id.txt_item_Item);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("Item")) tv.setText(boxNeedJSON.optJSONObject(position).get("Item").toString());

                tv = (TextView) convertView.findViewById(R.id.txt_item_Size);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("Size")) tv.setText(boxNeedJSON.optJSONObject(position).get("Size").toString());

                tv = (TextView) convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("ColorNo")) tv.setText(boxNeedJSON.optJSONObject(position).get("ColorNo").toString());

                tv = (TextView) convertView.findViewById(R.id.txt_item_Number);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("Number")) tv.setText(boxNeedJSON.optJSONObject(position).get("Number").toString());

                tv = (TextView) convertView.findViewById(R.id.txt_item_NeedNum);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("NeedNum")) tv.setText(boxNeedJSON.optJSONObject(position).get("NeedNum").toString());

                tv = (TextView) convertView.findViewById(R.id.txt_item_CurNum);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("CurNum")) tv.setText(boxNeedJSON.optJSONObject(position).get("CurNum").toString());

                tv = (TextView) convertView.findViewById(R.id.txt_item_State);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("State")) tv.setText(boxNeedJSON.optJSONObject(position).get("State").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_OrderNo);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("OrderNo"))  tv.setText(boxNeedJSON.optJSONObject(position).get("OrderNo").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_StyleNo);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("StyleNo")) tv.setText(boxNeedJSON.optJSONObject(position).get("StyleNo").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_PO);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("PO")) tv.setText(boxNeedJSON.optJSONObject(position).get("PO").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_Port);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("Port")) tv.setText(boxNeedJSON.optJSONObject(position).get("Port").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_BoxFormat);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("BoxFormat")) tv.setText(boxNeedJSON.optJSONObject(position).get("BoxFormat").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_Poid);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("Poid")) tv.setText(boxNeedJSON.optJSONObject(position).get("Poid").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_BoxType);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("BoxType")) tv.setText(boxNeedJSON.optJSONObject(position).get("BoxType").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_ColorNo);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("ColorNo")) tv.setText(boxNeedJSON.optJSONObject(position).get("ColorNo").toString());

                tv = (TextView) convertView.findViewById(R.id.tv_Size);// 显示文字
                if (boxNeedJSON.optJSONObject(position).has("Size")) tv.setText(boxNeedJSON.optJSONObject(position).get("Size").toString());


            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d(TAG,"DetailGridAdapter_position:"+position);
            return convertView;
        }
    }

    //修改包件数;
    private void showCallBox(){
        callType="Normal";
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_numkey, null);
        popupWindow = new PopupWindow(view,200,300);//参数为1.View 2.宽度 3.高度
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);//设置点击外部区域可以取消popupWindow
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        ((TextView)view.findViewById(R.id.tv_pop_title)).setText("辅料呼叫");
        ((TextView)view.findViewById(R.id.tv_pop_inputLbl)).setText("配套箱数");
        edt_checkReal=view.findViewById(R.id.edt_number);
        edt_number=view.findViewById(R.id.edt_number);
        view.findViewById(R.id.view_oneBtn).setOnClickListener(this);
        view.findViewById(R.id.view_twoBtn).setOnClickListener(this);
        view.findViewById(R.id.view_threeBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fourBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sixBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        view.findViewById(R.id.view_eightBtn).setOnClickListener(this);
        view.findViewById(R.id.view_nineBtn).setOnClickListener(this);
        view.findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        view.findViewById(R.id.view_delBtn).setOnClickListener(this);
        view.findViewById(R.id.view_clearBtn).setOnClickListener(this);
        view.findViewById(R.id.btn_AffirmCall).setOnClickListener(this);

        //控制屏幕宽度
        int deviationX=500,deviationY=370;
        DisplayMetrics dm = new DisplayMetrics();
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(mainLinerLayout,Gravity.CENTER,0,0);

    }

    //修改包件数;
    private void showManuCallBox(){
        callType="Manu";
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_numkey, null);
        popupWindow = new PopupWindow(view,200,300);//参数为1.View 2.宽度 3.高度
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);//设置点击外部区域可以取消popupWindow
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        view.findViewById(R.id.linerItem).setVisibility(View.VISIBLE);
        ((TextView)view.findViewById(R.id.tv_pop_title)).setText("无UCC辅料呼叫");
        ((TextView)view.findViewById(R.id.tv_pop_inputLbl)).setText("件数");
        edt_number=view.findViewById(R.id.edt_number);
        edt_number.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edt_checkReal!=null) edt_checkReal.setBackgroundColor(getResources().getColor(R.color.linen));
                edt_checkReal=(EditText)v;
                edt_checkReal.setBackgroundColor(getResources().getColor(R.color.aquamarine));
            }
        });
        edt_item=view.findViewById(R.id.edt_item);
        edt_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edt_checkReal!=null) edt_checkReal.setBackgroundColor(getResources().getColor(R.color.linen));
                edt_checkReal=(EditText)v;
                edt_checkReal.setBackgroundColor(getResources().getColor(R.color.aquamarine));
            }
        });
        edt_checkReal=view.findViewById(R.id.edt_item);
        edt_checkReal.setBackgroundColor(getResources().getColor(R.color.aquamarine));
        view.findViewById(R.id.view_oneBtn).setOnClickListener(this);
        view.findViewById(R.id.view_twoBtn).setOnClickListener(this);
        view.findViewById(R.id.view_threeBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fourBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sixBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        view.findViewById(R.id.view_eightBtn).setOnClickListener(this);
        view.findViewById(R.id.view_nineBtn).setOnClickListener(this);
        view.findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        view.findViewById(R.id.view_delBtn).setOnClickListener(this);
        view.findViewById(R.id.view_clearBtn).setOnClickListener(this);
        view.findViewById(R.id.btn_AffirmCall).setOnClickListener(this);

        //控制屏幕宽度
        int deviationX=500,deviationY=370;
        DisplayMetrics dm = new DisplayMetrics();
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(mainLinerLayout,Gravity.CENTER,0,0);

    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if (StrPenColor.indexOf("#")==0){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumeric(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
                if (StrPenColor.equals("Main") == true)
                    PenColor = getResources().getColor(R.color.text_main);
            }
        }
        return PenColor;
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getContext(), notification);
        r.play();

    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    Message msg = new Message();
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.length()>0) {
                            if (OperType.equals("OrderList")) {
                                orderJSON = jsonArray;
                                msg.what = msgGetOrderListOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("ColorList")) {
                                orderJSON = jsonArray;
                                msg.what = msgGetColorListOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("Detail")) {
                                detailJSON = jsonArray;
                                msg.what = msgGetOrderListOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("AccNeed")) {
                                boxNeedJSON= jsonArray;
                                msg.what = msgGetBoxNeedListOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else if (OperType.equals("CallNeedAcc")){
                                //显示预排单;
                                resultJSON=jsonArray;
                                msg.what = MSG_CallAcc;
                                Bundle bundle=new Bundle();
                                if (resultJSON.optJSONObject(0).has("NeedRefresh"))
                                    bundle.putString("NeedRefresh",resultJSON.optJSONObject(0).getString("NeedRefresh"));
                                if (resultJSON.optJSONObject(0).has("Result"))
                                    bundle.putString("Result",resultJSON.optJSONObject(0).getString("Result"));
                                if (resultJSON.optJSONObject(0).has("ResultInfo"))
                                    bundle.putString("ResultInfo",resultJSON.optJSONObject(0).getString("ResultInfo"));
                                msg.setData(bundle);
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else  if (OperType.equals("DepartList")){
                                departJSON=jsonArray;
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("TypeGroup")==true) {
                            departJSON = jsonArray;
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    }
                    reentrantLock.unlock();
                } catch (Exception e) {
                    reentrantLock.unlock();
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }

        };
        new Thread(run).start();

    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                if (waitDialog.isShowing()) waitDialog.dismiss();
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERROR:
                        Bundle bundle1=msg.getData();
                        curToast.setText(bundle1.getString("HintInfo"));
                        curToast.show();
                        break;
                    case MSG_CallAcc:
                        Bundle bundle=msg.getData();
                        System.out.println("MSG_CallBox:"+bundle);
                        if (bundle.getString("Result","N").equals("Y")){
                            if (popupWindow != null && popupWindow.isShowing()) popupWindow.dismiss();
                            //根据需要进的功能调用对应模块
                            if (bundle.getString("NeedRefresh","").equals("Y")) SearchDetail();
                            String resultinfo=bundle.getString("ResultInfo","呼叫成功");
                            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                    .setTitle("系统提示").setMessage(resultinfo)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                            alertDialog.show(); // 显示对话框
                        } else{
                            String resultinfo=bundle.getString("ResultInfo","操作有误");
                            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                    .setTitle("系统提示").setMessage(resultinfo)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                            alertDialog.show(); // 显示对话框
                        }
                        break;
                    case msgDetail:
                        //显示预排单;
                        fillFormtext();
                        break;
                    case msgGetColorListOver:
                    case msgGetOrderListOver:
                        //准备显示明细
                        detailJSON=orderJSON;
                        SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(getContext());
                        lv_Detail.setAdapter(selectTempletListAdapter);
                        break;
                    case msgGetBoxNeedListOver:
                        DetailListAdapter detailListAdapter = new DetailListAdapter(getContext());
                        detailList.setAdapter(detailListAdapter);
                        break;
                    default:
                        break;
                }
            }
        }
    };



    //清除界面显示内容
    private void clearFormText(){


    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (detailJSON.length()>0)
        {
            try {

                if (detailJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                    mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(detailJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.out.println("fillFormtext----------edt_barcode置焦点");

    }

    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println("FragmentD 设置焦点-------------------------------1.Start");
        refreshDepartData();
        //更新当前组别
        edt_WorkGroup.setText(curDepart);
        System.out.println("FragmentD 设置焦点-------------------------------1.End");
    }
}
